﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
	[CommandHandler("addlistener")]
	public class AddConnectionListener : CommandHandler
	{
		public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
		{
			if (message.UnnamedArguments.Count == 1)
			{
				if (!Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.AddConnectionListenerPermission)))
					return new BotReturnStatus(false, Security.Permission.GetDeniedString(typeof(Security.Permissions.AddConnectionListenerPermission)));

				System.Net.IPEndPoint iep = null;
				System.Net.DnsEndPoint dep = null;
				bool parseSuccess = NetfractionHub.Network.IPHelper.ParseIPEndPoint(message.UnnamedArguments[0].Trim(), out iep);

				if (!parseSuccess)
				{
					parseSuccess = NetfractionHub.Network.IPHelper.ParseDnsEndPoint(message.UnnamedArguments[0].Trim(), out dep);

					if (!parseSuccess)
						return new BotReturnStatus(false, "Incorrect format. Both an IP or host name, and a port must be specified, seperated by a colon e.g. xyz.com:4501 for a host name, or 127.0.0.1:4501 for IPv4 or [::1]:4501 for IPv6.");
				}

				if (iep != null)
				{
					if (!Settings.HubSettings.HubConnection.ListeningEndPoints.Contains(iep))
						Settings.HubSettings.HubConnection.ListeningEndPoints.Add(iep);

					Network.ConnectionListner.GetInstance().AddListener(iep);

					return new BotReturnStatus(true, string.Format("The hub is now listening on the following address: {0}", iep.ToString()));
				}
				else if (dep != null)
				{
					if (!Settings.HubSettings.HubConnection.ListeningEndPoints.Contains(dep))
						Settings.HubSettings.HubConnection.ListeningEndPoints.Add(dep);

					foreach (var ip in System.Net.Dns.GetHostAddresses(dep.Host))
					{
						Network.ConnectionListner.GetInstance().AddListener(new System.Net.IPEndPoint(ip, dep.Port));
					}

					return new BotReturnStatus(true, string.Format("The hub is now listening on the following address: {0}", dep.ToString()));
				}
				else
				{
					return new BotReturnStatus(false, "Incorrect format or address could not be found.");
				}
			}
			else
				return new BotReturnStatus(false);
		}
	}
}
